import { messages } from "share/common";
import React from "react";
import { Button, Table } from "antd";
import { reasonsColumns } from "./reasons-columns";
import ReasonsConfigEdit from "./reasons-config-edit";
import SlideFrame from "components/slide-frame";

export default class ReasonSetting extends React.Component {
  constructor(props) {
    super(props);
    let reasonDatas;
    if ("value" in props) {
      reasonDatas = props.value;
    }
    this.state = {
      reasonDatas,
      showSlideFrame: false,
      editData: {},
      pagination: {
        pageSize: 15,
      },
      id: props.id,
    };
  }

  onEdit = (...args) => {
    const [text, row, index] = args;
    this.setState({ showSlideFrame: true, editData: Object.assign({}, row, { index }) });
  };

  onAddReason = () => {
    this.setState({ showSlideFrame: true, editData: {} });
  };

  onAfterClose = ({ type, data }) => {
    typeof this[type] === "function" && this[type](data);
  };

  //新增
  addData = (data) => {
    const reasonDatas = [...this.state.reasonDatas].concat([data]);
    this.setState({ reasonDatas, showSlideFrame: false }, this.onChange);
  };

  alterData = (data) => {
    const reasonDatas = [...this.state.reasonDatas];
    const { index } = data;
    reasonDatas[index] = data;
    this.setState({ reasonDatas, showSlideFrame: false }, this.onChange);
  };

  onChange = () => {
    this.props.onChange(this.state.reasonDatas);
  };

  onClose = () => {
    this.setState({ showSlideFrame: false });
  };

  render = () => {
    const { reasonDatas, showSlideFrame, editData, pagination, id } = this.state;
    const { title, subTitle, companyOID, source } = this.props;
    const isAdd = !Object.keys(editData).length;
    return (
      <div className="reasons-setting">
        {title && <h2>{title}</h2>}
        {subTitle && <a className="a-line-bottom">{subTitle}</a>}
        <Button type="primary" onClick={() => this.setState({ showSlideFrame: true, editData: {} })}>
          {messages("common.next") /*新建*/}
        </Button>
        <Table columns={reasonsColumns(this.onEdit)} dataSource={reasonDatas} pagination={pagination} />
        {showSlideFrame && (
          <SlideFrame
            title={isAdd ? messages("supplier-1.key857") /*新增理由*/ : messages("supplier-1.key858") /*编辑理由*/}
            show={showSlideFrame}
            content={ReasonsConfigEdit}
            params={{ editData, ...{ isAdd, id, companyOID, source } }}
            afterClose={this.onAfterClose}
            onClose={() => this.setState({ showSlideFrame: false })}
          />
        )}
      </div>
    );
  };
}
